package com.file.service;

import com.file.util.FileUtil;
import org.springframework.stereotype.Service;

import javax.servlet.http.*;
import java.io.*;

/**
 * Created by hui on 2017/12/4.
 */

@Service
public class DownloadService extends HttpServlet {

    private void downFile(HttpServletRequest request, HttpServletResponse response, String filename, String path) {
        if (filename != null) {
            FileInputStream is = null;
            BufferedInputStream bs = null;
            OutputStream os = null;
            try {
                File file = new File(path);
                if (file.exists()) {
                    //判断文件类型 //设置Headers
                    FileUtil.setDownloadHeaderContentType(response, filename);
                    filename = FileUtil.formatFileName(request, filename);
                    //设置下载的文件的名称-该方式已解决中文乱码问题
                    response.setHeader("Content-Disposition", "attachment;filename=" + filename);
                    is = new FileInputStream(file);
                    bs = new BufferedInputStream(is);
                    os = response.getOutputStream();
                    byte[] buffer = new byte[1024];
                    int len = 0;
                    while ((len = bs.read(buffer)) != -1) {
                        os.write(buffer, 0, len);
                    }
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            } finally {
                try {
                    if (is != null) is.close();
                    if (bs != null) bs.close();
                    if (os != null) {
                        os.flush();
                        os.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}